package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.PaasStageEntity;
import com.xbongbong.paas.domain.entity.StageProcessEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.FormSubDataUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.LogicalSymbolEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.StageTypeEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.StageProcessModel;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataDTO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.redis.RedisTimeConstant;
import com.xbongbong.paas.service.stage.StageHandle;
import com.xbongbong.paas.service.stage.StageHandleFactory;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.dictionary.pojo.DictionaryPojo;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.businessrule.enums.RuleOperatorBusinessFieldEnum;
import com.xbongbong.pro.enums.businessrule.enums.RuleOperatorFieldEnum;
import com.xbongbong.pro.enums.businessrule.enums.RuleValueTypeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemLabelErrorCodeEnum;
import com.xbongbong.pro.formexplain.pojo.FieldAndLogicPojo;
import com.xbongbong.pro.formexplain.pojo.LogicPojo;
import com.xbongbong.pro.formexplain.pojo.ValueTypePojo;
import com.xbongbong.pro.team.TeamFieldExplainPOJO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DataDictionaryEntity;
import com.xbongbong.saas.domain.entity.FundAccountEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.enums.ClueRuleSettingEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.RuleSettingEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.ContractStatusEnum;
import com.xbongbong.saas.enums.dictionary.CustomerTypeEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.dictionary.ExpressStatusEnum;
import com.xbongbong.saas.enums.dictionary.HasRedEnum;
import com.xbongbong.saas.enums.dictionary.IsRedEnum;
import com.xbongbong.saas.enums.dictionary.NewEnum;
import com.xbongbong.saas.enums.dictionary.PublicEnum;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.FundAccountModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.FundUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/5/25 14:45
 * @since v1.0
 */
@Component
public class ProFormHelp {

    private static final Logger LOG = LoggerFactory.getLogger(ProFormHelp.class);

    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private StageHandleFactory stageHandleFactory;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private PaasRedisHelper paasRedisHelper;
    @Resource
    private FundAccountModel fundAccountModel;
    @Resource
    private LabelModel labelModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private DistributorMarkHelp distributorMarkHelp;
    @Resource
    private StageProcessModel stageProcessModel;
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * 设置 新建、复制处理下拉选选项
     * @param fieldAttrEntity
     * @param paasFormEntityExt
     * @return
     * @throws XbbException
     */
    public List<ItemPoJo> setItem(FieldAttrEntity fieldAttrEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        List<ItemPoJo> itemList = fieldAttrEntity.getItems();
        if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttrEntity.getFieldType())) {
            List<ItemPoJo> newItemList = getEnableStageComboItems(paasFormEntityExt.getSaasMark(), paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(), paasFormEntityExt.getId());
            //设置颜色
            Map<Object, String> colorMap = new HashMap<>();
            itemList.forEach(item -> colorMap.put(item.getValue(), item.getColor()));
            newItemList.forEach(item -> item.setColor(colorMap.get(item.getValue())));
            return newItemList;
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormEntityExt.getSaasMark())) {
            itemList = getItem(fieldAttrEntity, paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(),paasFormEntityExt.getId());
        }
        return itemList;
    }

    /**
     * 设置阶段 编辑处理下拉选选项
     * @param fieldAttrEntity
     * @param paasFormEntityExt
     * @return
     * @throws XbbException
     */
    public List<ItemPoJo> setItem(FieldAttrEntity fieldAttrEntity, PaasFormEntityExt paasFormEntityExt, JSONObject data) throws XbbException {
        List<ItemPoJo> itemList = fieldAttrEntity.getItems();
        if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())){
            List<ItemPoJo> newItemList = getEditStageComboItems(fieldAttrEntity, paasFormEntityExt.getSaasMark(), paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(), paasFormEntityExt.getId(), data);
            Map<Object, String> colorMap = new HashMap<>();
            itemList.forEach(item -> colorMap.put(item.getValue(), item.getColor()));
            newItemList.forEach(item -> item.setColor(colorMap.get(item.getValue())));
            return newItemList;
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormEntityExt.getSaasMark())) {
            itemList = getItem(fieldAttrEntity, paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(),paasFormEntityExt.getId());
        }
        return itemList;
    }

    /**
     * 获取相应流程版本的阶段信息
     * @param fieldAttrEntity
     * @param saasMark
     * @param businessType
     * @param corpid
     * @param formId
     * @param data
     * @return
     * @throws XbbException
     */
    public List<ItemPoJo> getEditStageComboItems(FieldAttrEntity fieldAttrEntity, Integer saasMark, Integer businessType, String corpid, Long formId, JSONObject data) throws XbbException{
        String code = FastJsonHelper.getStringOrDefaultFromFormData(data, fieldAttrEntity.getAttr(), "");
        Long stageProcessId = FastJsonHelper.getLongOrDefaultFromFormData(data, PaasStageEnum.STAGE_PROCESS_ID.getAttr(), BasicConstant.ZERO_LONG);
        //如果没有stageProcessId 说明是迁移版本 去迁移版本拿stageProcessId
        if (Objects.equals(stageProcessId, BasicConstant.ZERO_LONG)) {
            StageProcessEntity stageProcessEntity = stageProcessModel.getByTransferVersion(corpid, formId, BasicConstant.ONE);
            if (Objects.nonNull(stageProcessEntity)) {
                stageProcessId = stageProcessEntity.getId();
            }
        }
        //如果code为空 返回当前启用版本
        List<ItemPoJo> newItemList;
        if (StringUtil.isEmpty(code)) {
            newItemList = getEnableStageComboItems(saasMark, businessType, corpid, formId);
        } else {
            newItemList = getItemPojoForStageEntity(corpid, formId, stageProcessId, businessType, saasMark, null);
        }
        Map<String, String> colorMap = new HashMap<>();
        fieldAttrEntity.getItems().forEach(item -> colorMap.put(item.getText(), item.getColor()));
        newItemList.forEach(item -> item.setColor(colorMap.get(item.getText())));
        return newItemList;
    }

    /**
     * 设置
     * @param fieldAttrEntity
     * @param paasFormEntityExt
     * @return
     * @throws XbbException
     */
    public List<ItemPoJo> setItemAndComboItems(FieldAttrEntity fieldAttrEntity, PaasFormEntityExt paasFormEntityExt) throws XbbException {
        List<ItemPoJo> itemList = fieldAttrEntity.getItems();
        if (Objects.equals(FieldTypeEnum.STAGE_THRUSTER.getType(), fieldAttrEntity.getFieldType())) {
            List<ItemPoJo> newItemList = getEnableStageComboItems(paasFormEntityExt.getSaasMark(), paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(), paasFormEntityExt.getId());
            //处理颜色
            Map<Object, String> colorMap = new HashMap<>();
            itemList.forEach(item -> colorMap.put(item.getValue(), item.getColor()));
            newItemList.forEach(item -> item.setColor(colorMap.get(item.getValue())));
            return newItemList;
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), paasFormEntityExt.getSaasMark())) {
            if (Objects.equals(FieldTypeEnum.COMBO_NUM.getType(), fieldAttrEntity.getFieldType())) {
                itemList = getComboItems(fieldAttrEntity, paasFormEntityExt.getBusinessType());
            } else {
                itemList = getItem(fieldAttrEntity, paasFormEntityExt.getBusinessType(), paasFormEntityExt.getCorpid(),paasFormEntityExt.getId());
            }
        }
        return itemList;
    }
    /**
     * 获取客户状态，合同状态，物流公司
     * @param fieldAttrEntity 字段
     * @param formId
     * @return 属性列表
     * @throws XbbException
     */
    public List<ItemPoJo> getItem(FieldAttrEntity fieldAttrEntity, Integer businessType, String corpid, Long formId) throws XbbException {
        List<ItemPoJo> itemList = fieldAttrEntity.getItems();
        if (Objects.isNull(itemList)) {
            itemList = new ArrayList<>();
        }
        itemList = getItem(businessType, corpid, formId, itemList, fieldAttrEntity);
        return itemList;
    }

    public List<ItemPoJo> getItem(Integer businessType, String corpid, Long formId, List<ItemPoJo> itemList, FieldAttrEntity fieldAttrEntity) throws XbbException {
        String attr = fieldAttrEntity.getAttr();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<ItemPoJo> dictionaryItemList = new ArrayList<>();
        boolean itemUpdate = false;
        switch (xbbRefTypeEnum) {
            case CUSTOMER_MANAGEMENT:
                // 客户状态
                if (Objects.equals(attr, CustomerManagementEnum.TYPE.getAttr())) {
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STATUS, corpid, formId);
                    dictionaryItemList.forEach(item -> {
                        if (Objects.equals(item.getValue().toString(), CustomerTypeEnum.TRANSACTION_CUSTOMER.getCode()) ||
                                Objects.equals(item.getValue().toString(), CustomerTypeEnum.LOYAL_CUSTOMERS.getCode()) ||
                                Objects.equals(item.getValue().toString(), CustomerTypeEnum.INVALID_CUSTOMER.getCode())){
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        }
                    });
                    itemUpdate = true;
                }else if (Objects.equals(attr,CustomerManagementEnum.CUSTOMER_STAGE.getAttr())){
                    StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                    dictionaryItemList = stageHandle.getItemList(corpid, formId, BasicConstant.ONE);
                    dictionaryItemList.forEach(item -> {
                        if (Objects.equals(item.getStageType(), StageTypeEnum.SUCCESS_STAGE.getType())){
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        }
                        item.setValue(item.getValue().toString());
                    });
                    itemUpdate = true;
                }else if (Objects.equals(attr, CustomerManagementEnum.WASTAGE.getAttr())){
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CUSTOMER_STAGE_WASTAGE, corpid, formId);
                    itemUpdate = true;
                }
                break;
            case CONTRACT:
                Integer distributorMark = distributorMarkHelp.getDistributorMark(formId, corpid);
                // 合同状态
                if (Objects.equals(attr, ContractEnum.STATUS.getAttr()) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(),distributorMark)) {
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CONTRACT_STATUS, corpid, formId);
                    dictionaryItemList.forEach(item -> {
                        if (Objects.equals(item.getValue().toString(), ContractStatusEnum.TERMINATION.getCode())){
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        }
                    });
                    itemUpdate = true;
                } else if (Objects.equals(attr, ContractEnum.EXPRESS_NAME.getAttr())) {
                    // 物流公司
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.EXPRESS_NAME, corpid, formId);
                    itemUpdate = true;
                }else if (Objects.equals(attr, ContractEnum.EXPRESS_STATUS.getAttr()) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(),distributorMark)){
                    // 合同发货状态不允许编辑删除
                    List<String> codes = ExpressStatusEnum.getAllCode();
                    itemList.forEach(item -> {
                        if (codes.contains(item.getValue())) {
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        } else {
                            item.setNoDel(0);
                            item.setNoEdit(0);
                        }
                    });
                }
                break;
            case SALES_OPPORTUNITY:
                // 销售阶段下拉项设置不允许编辑删除，流失原因不允许移动
                if (Objects.equals(attr, SalesOpportunityEnum.SALE_STAGE.getAttr())){
                    StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                    dictionaryItemList = stageHandle.getItemList(corpid,formId, BasicConstant.ONE);
                    dictionaryItemList.forEach(item -> {
                        if (Objects.equals(item.getStageType(), StageTypeEnum.FAIL_STAGE.getType())){
                            List<String> fields = new ArrayList<>();
                            fields.add(SalesOpportunityEnum.WASTAGE.getAttr());
                            fields.add(SalesOpportunityEnum.WASTAGE_MEMO.getAttr());
                            item.setFieldMap(fields);
                            item.setNoMove(1);
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        } else if (Objects.equals(item.getStageType(), StageTypeEnum.SUCCESS_STAGE.getType())){
                            item.setNoMove(1);
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        } else if (Objects.equals(item.getStageType(), StageTypeEnum.CANCEL_STAGE.getType())){
                            item.setNoMove(1);
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        }
                        item.setValue(item.getValue().toString());
                    });
                    itemUpdate = true;
                }else if (Objects.equals(attr, SalesOpportunityEnum.WASTAGE.getAttr())){
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.SALE_STAGE_WASTAGE, corpid, formId);
                    itemUpdate = true;
                }
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
            case ORDER_OUTSTOCK:
                // 物流公司
                if (Objects.equals(attr, OutstockEnum.EXPRESS_NAME.getAttr())) {
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.EXPRESS_NAME, corpid, formId);
                    itemUpdate = true;
                }
                break;
            case COMMUNICATE_PLAN:
                // 延期原因
                if (Objects.equals(attr, CommunicatePlanEnum.DELAY_CAUSE.getAttr())) {
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.DELAY_CAUSE, corpid, formId);
                    itemUpdate = true;
                }else if (Objects.equals(attr, CommunicatePlanEnum.NOTIFY_TYPE.getAttr())){
                    // 销售阶段下拉项设置不允许编辑删除，流失原因不允许移动
                    itemList.forEach(item -> {
                        item.setNoMove(1);
                        item.setNoDel(1);
                        item.setNoEdit(1);
                    });
                }
                break;
            case PAYMENT:
                // 回款状态所有选项不允许修改删除和修改
                if (Objects.equals(attr, PaymentEnum.STATUS.getAttr())){
                    itemList.forEach(item -> {
                        item.setNoDel(1);
                        item.setNoEdit(1);
                    });
                }
                break;
            case PAY_PLAN:
                // 付款状态所有选项不允许修改删除和修改
                if (Objects.equals(attr, PayPlanEnum.STATUS.getAttr())){
                    itemList.forEach(item -> {
                        item.setNoDel(1);
                        item.setNoEdit(1);
                    });
                }
                break;
            case BOM_BILL:
                // bom单状态所有选项不允许修改删除和修改
                if (Objects.equals(attr, BomBillEnum.STATUS.getAttr())){
                    itemList.forEach(item -> {
                        item.setNoDel(1);
                        item.setNoEdit(1);
                    });
                }
                break;
            case INVOICE:
                if(Objects.equals(attr, InvoiceEnum.PAYMENT_RELATIONSHIP.getAttr())){
                    paasRedisHelper.setValue(InvoiceConstant.TAG_PAYMENT_RELATIONSHIP,corpid,fieldAttrEntity, TimeConstant.TINY_DURATION);
                }
                if(Objects.equals(attr,InvoiceEnum.PAYMENT_ID.getAttr()) || Objects.equals(attr,InvoiceEnum.PAYMENT_SHEET_ID.getAttr())){
                    String fieldAttr = paasRedisHelper.getValue(InvoiceConstant.TAG_PAYMENT_RELATIONSHIP,corpid);
                    FieldAttrEntity paymentRelationshipField = null;
                    if(Objects.isNull(fieldAttr)){
                        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(RedundantTemplateTypeEnum.INVOICE.getCode(), corpid);
                        if (Objects.isNull(paasFormExplainEntity)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                        }
                        String explains = paasFormExplainEntity.getExplains();
                        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                        paymentRelationshipField = explainMap.get(InvoiceEnum.PAYMENT_RELATIONSHIP.getAttr());
                    }else {
                        paymentRelationshipField= JSONObject.parseObject(fieldAttr,FieldAttrEntity.class);
                    }
                    if(Objects.nonNull(paymentRelationshipField)) {
                        fieldAttrEntity.setVisible(paymentRelationshipField.getVisible());
                        fieldAttrEntity.setVisibleScopeEnable(paymentRelationshipField.getVisibleScopeEnable());
                        fieldAttrEntity.setVisibleScopeRule(paymentRelationshipField.getVisibleScopeRule());
                        fieldAttrEntity.setEditable(paymentRelationshipField.getEditable());
                        fieldAttrEntity.setEditableAdvanceEnable(paymentRelationshipField.getEditableAdvanceEnable());
                        fieldAttrEntity.setEditableRule(paymentRelationshipField.getEditableRule());
                    }
                }
                break;
            case PURCHASE_INVOICE:
                if(Objects.equals(attr, PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr())){
                    paasRedisHelper.setValue(InvoiceConstant.TAG_PAY_RELATIONSHIP,corpid,fieldAttrEntity, TimeConstant.TINY_DURATION);
                }
                if(Objects.equals(attr,PurchaseInvoiceEnum.PAY_PLAN_ID.getAttr()) || Objects.equals(attr,PurchaseInvoiceEnum.PAY_SHEET_ID.getAttr())){
                    String fieldAttr = paasRedisHelper.getValue(InvoiceConstant.TAG_PAY_RELATIONSHIP,corpid);
                    FieldAttrEntity payRelationshipField = null;
                    if(Objects.isNull(fieldAttr)){
                        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(RedundantTemplateTypeEnum.PURCHASE_INVOICE.getCode(), corpid);
                        if (Objects.isNull(paasFormExplainEntity)) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                        }
                        String explains = paasFormExplainEntity.getExplains();
                        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                        payRelationshipField = explainMap.get(PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr());
                    }else {
                        payRelationshipField= JSONObject.parseObject(fieldAttr,FieldAttrEntity.class);
                    }
                    if(Objects.nonNull(payRelationshipField)) {
                        fieldAttrEntity.setVisible(payRelationshipField.getVisible());
                        fieldAttrEntity.setVisibleScopeEnable(payRelationshipField.getVisibleScopeEnable());
                        fieldAttrEntity.setVisibleScopeRule(payRelationshipField.getVisibleScopeRule());
                        fieldAttrEntity.setEditable(payRelationshipField.getEditable());
                        fieldAttrEntity.setEditableAdvanceEnable(payRelationshipField.getEditableAdvanceEnable());
                        fieldAttrEntity.setEditableRule(payRelationshipField.getEditableRule());
                    }
                }
                break;
            case PAY_SHEET:
            case PAYMENT_SHEET:
            case OTHER_INCOME:
            case OTHER_EXPENSE:
            case FUND_TRANSFER:
                //资金账户对应saasAttr
                List<String> fundAccountSaasAttrList = FundUtil.getFundAccountSaasAttrList();
                if (fundAccountSaasAttrList.contains(fieldAttrEntity.getSaasAttr())){
                    itemList = handleFundAccountItems(corpid, businessType,fieldAttrEntity.getItems());
                }
                break;
            case CLUE:
                if (Objects.equals(attr,ClueEnum.CLUE_STAGE.getAttr())){
                    StageHandle stageHandle = stageHandleFactory.getStageHandle(SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.CLUE.getCode());
                    dictionaryItemList = stageHandle.getItemList(corpid, formId, BasicConstant.ONE);
                    dictionaryItemList.forEach(item -> {
                        if (Objects.equals(item.getStageType(), StageTypeEnum.FAIL_STAGE.getType())){
                            item.setNoMove(1);
                            item.setNoDel(1);
                            item.setNoEdit(1);
                        }
                        item.setValue(item.getValue().toString());
                    });
                    itemUpdate = true;
                }else if (Objects.equals(attr, ClueEnum.INVALID_REASON.getAttr())){
                    dictionaryItemList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.CLUE_STAGE_INVALID, corpid, formId);
                    itemUpdate = true;
                }
                break;
            default:
                break;
        }
        if (itemUpdate) {
            Set<Object> checkedSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Object, List<String>> fieldMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Object, Map<String, List<ItemPoJo>>> subAttrListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Object, String> colorMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (ItemPoJo itemPoJo : itemList) {
                if (Objects.equals(itemPoJo.getChecked(), true)) {
                    checkedSet.add(itemPoJo.getValue());
                }
                if (Objects.nonNull(itemPoJo.getFieldMap()) && !itemPoJo.getFieldMap().isEmpty()) {
                    fieldMap.put(itemPoJo.getValue(), itemPoJo.getFieldMap());
                }
                if (Objects.nonNull(itemPoJo.getSubAttrList()) && !itemPoJo.getSubAttrList().isEmpty()) {
                    subAttrListMap.put(itemPoJo.getValue(), itemPoJo.getSubAttrList());
                }
                if (Objects.nonNull(itemPoJo.getColor()) && !itemPoJo.getColor().isEmpty()){
                    colorMap.put(itemPoJo.getValue(), itemPoJo.getColor());
                }
            }
            for (ItemPoJo itemPoJo : dictionaryItemList) {
                if (checkedSet.contains(itemPoJo.getValue())) {
                    itemPoJo.setChecked(true);
                }
                if (fieldMap.containsKey(itemPoJo.getValue())) {
                    itemPoJo.setFieldMap(fieldMap.get(itemPoJo.getValue()));
                }
                if (subAttrListMap.containsKey(itemPoJo.getValue())) {
                    itemPoJo.setSubAttrList(subAttrListMap.get(itemPoJo.getValue()));
                }
                if (colorMap.containsKey(itemPoJo.getValue())){
                    itemPoJo.setColor(colorMap.get(itemPoJo.getValue()));
                }
            }
            return dictionaryItemList;
        }
        return itemList;
    }

    /**
     * 获取字段解释，包括工单的
     * @param corpid 公司id
     * @param formId 表单id
     * @param businessType 业务类型
     * @return
     * @throws XbbException
     */
    public PaasFormExplainEntity getExplainEntity(String corpid, Long formId, Integer businessType) throws XbbException{
        PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            WorkOrderExplainEntityExt workOrderExplainEntityExt = new WorkOrderExplainEntityExt();
            if (Objects.equals(formId, 0L)) {
                WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getDefaultAllListExplain(corpid);
                BeanUtil.copyProperties(workOrderExplainEntity, workOrderExplainEntityExt);
            } else {
                workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
            }
            if(workOrderExplainEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
            paasFormExplainEntity.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormExplainEntity.setSaasMark(SaasMarkEnum.SAAS.getCode());
            paasFormExplainEntity.setDistributorMark(DistributorMarkEnum.OTHER.getCode());
        } else if (Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType)){
            //工作报告
            if (Objects.equals(formId, 0L) || Objects.isNull(formId)) {
                paasFormExplainEntity = paasFormExplainModel.getWorkReportDefaultAllListExplain();
                if (Objects.isNull(paasFormExplainEntity)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
            } else {
                Map<String, Object> paramMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paramMap.put(ParameterConstant.FORMID,formId);
                paramMap.put(ParameterConstant.CORPID,corpid);
                paramMap.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
                List<PaasFormExplainEntity> list = paasFormExplainModel.list(paramMap);
                if (list == null || list.isEmpty()) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                paasFormExplainEntity = list.get(0);
            }
        } else if (Objects.equals(XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.WRITE_OFF_RECORD.getCode(), businessType)){
            paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);
        }else if (Objects.equals(formId, 0L) && Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2.getCode(), businessType)) {
            paasFormExplainEntity = paasFormExplainModel.getSystemDefaultExplain(businessType);

        }else {
            paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        }
        if(paasFormExplainEntity == null) {
            LOG.error("获取表单解释异常，corpid={}，formId={}，businessType={}", corpid, formId, businessType);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        return paasFormExplainEntity;
    }

    /**
     * 获取非工单的字段解释
     * @param formIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, PaasFormExplainEntity> getFormExplainMap(Collection formIdList, String corpid) throws XbbException {
        Map<Long, PaasFormExplainEntity> formExplainMap = new HashMap<>(formIdList.size());
        if (formIdList.isEmpty()) {
            return formExplainMap;
        }
        if (!formIdList.isEmpty()) {
            Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            explainParam.put("formIdIn", formIdList);
            explainParam.put(StringConstant.CORPID, corpid);
            explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(explainParam);
            if(formExplainList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            formExplainList.forEach((item)->{
                formExplainMap.put(item.getFormId(), item);
            });
        }
        return formExplainMap;
    }

    /**
     * Description: 获取团队相关字段解释
     * @param corpid
     * @param formId
     * @param businessType
     * @return com.xbongbong.pro.team.TeamFieldExplainPOJO
     * @throws
     * @author 魏荣杰
     * @date 2022/1/10 10:11
     * @since
     */
    public TeamFieldExplainPOJO getTeamFieldExplain(String corpid, Long formId, Integer businessType) throws XbbException {
        // 负责人解释
        FieldAttrEntity ownerField = new FieldAttrEntity();
        // 协同人解释
        FieldAttrEntity coUserField = new FieldAttrEntity();
        if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
            WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(workOrderExplainEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(workOrderExplainEntityExt.getExplains(), null);
            ownerField = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
            coUserField = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        } else {
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if (Objects.isNull(paasFormExplainEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
            ownerField = explainMap.get(FieldTypeEnum.OWNERID.getAlias());
            coUserField = explainMap.get(FieldTypeEnum.COUSERID.getAlias());
        }
        //目前预收款和预付款表单解释没有存协同人，但是预收款的团队变更又是跟着客户的团队，预付款的团队变更又是跟着供应商的团队，所以这边协同人解释直接用客户/供应商解释.
        //但是由于查询太麻烦了，直接写死一个默认解释
        if (Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), businessType)) {
            FieldAttrEntity defalutCoUserField = new FieldAttrEntity();
            defalutCoUserField.setFieldType(FieldTypeEnum.COUSERID.getType());
            defalutCoUserField.setAttr(FieldTypeEnum.COUSERID.getAlias());
            coUserField = defalutCoUserField;
        }
        TeamFieldExplainPOJO teamFieldExplainPOJO = new TeamFieldExplainPOJO();
        teamFieldExplainPOJO.setOwnerField(ownerField);
        teamFieldExplainPOJO.setCoUserField(coUserField);
        return teamFieldExplainPOJO;
    }

    /**
     * 获取表单解释的集合，子表单字段将返回 {"subForm_1.text_1":{字段属性}}
     * @param formIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, Map<String, FieldAttrEntity>> getFormFieldMap(Collection formIdList, String corpid) throws XbbException {

        Map<Long, PaasFormExplainEntity> formExplainEntityMap = getFormExplainMap(formIdList, corpid);
        Map<Long, Map<String, FieldAttrEntity>> explainMap = new HashMap<>(formExplainEntityMap.size());
        formExplainEntityMap.forEach((key, entity)->{
            Map<String, FieldAttrEntity> map = ExplainUtil.getExplainMap(entity.getExplains());
            FieldAttrEntity fieldAttrEntity = getDataIdAttr();
            map.put(FieldTypeEnum.DATAID.getAlias(), fieldAttrEntity);
            explainMap.put(key, map);
        });
        return explainMap;
    }

    /**
     * 获取工单解释的集合，子表单字段将返回 {"subForm_1.text_1":{字段属性}}
     * @param formIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, Map<String, FieldAttrEntity>> getWorkOrderFormFieldMap(Collection formIdList, String corpid) throws XbbException {
        Map<Long, WorkOrderExplainEntity> formExplainEntityMap = getWorkOrderFormExplainMap(formIdList, corpid);
        Map<Long, Map<String, FieldAttrEntity>> workOrderFieldMap = new HashMap<>(formExplainEntityMap.size());
        formExplainEntityMap.forEach((key, entity)->{
            Map<String, FieldAttrEntity> map = ExplainUtil.getExplainMap(entity.getExplains());
            FieldAttrEntity fieldAttrEntity = getDataIdAttr();
            map.put(FieldTypeEnum.DATAID.getAlias(), fieldAttrEntity);
            workOrderFieldMap.put(key, map);
        });
        return workOrderFieldMap;
    }


    /**
     * 获取工单的字段解释
     * @param workOrderFormIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, WorkOrderExplainEntity> getWorkOrderFormExplainMap(Collection workOrderFormIdList, String corpid) throws XbbException {
        Map<Long, WorkOrderExplainEntity> workOrderExplainMap = new HashMap<>(workOrderFormIdList.size());
        if (workOrderFormIdList.isEmpty()) {
            return workOrderExplainMap;
        }
        if (!workOrderFormIdList.isEmpty()) {
            Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            explainParam.put("formIdIn", workOrderFormIdList);
            explainParam.put(StringConstant.CORPID, corpid);
            explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
            List<WorkOrderExplainEntity> formExplainList = workOrderExplainModel.list(explainParam);
            if(formExplainList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            formExplainList.forEach((item)->{
                workOrderExplainMap.put(item.getFormId(), item);
            });
        }
        return workOrderExplainMap;
    }


    public static void setDataIdAttr(Map<String, FieldAttrEntity> explainMap) {
        FieldAttrEntity fieldAttrEntity = getDataIdAttr();
        explainMap.put(FieldTypeEnum.DATAID.getAlias(), fieldAttrEntity);
    }


    private static FieldAttrEntity getDataIdAttr() {
        FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
        fieldAttrEntity.setAttr(FieldTypeEnum.DATAID.getAlias());
        fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(PaasConstant.DATA_ID_MEMO));
        fieldAttrEntity.setFieldType(FieldTypeEnum.DATAID.getType());
        return fieldAttrEntity;
    }
    /**
     * 获取表单主体，包括工单的
     * @param corpid 公司id
     * @param formId 表单id
     * @param businessType 业务类型
     * @return
     * @throws XbbException
     */
    public PaasFormEntity getPaasForm(Long formId, Integer businessType, String corpid) throws XbbException {
        PaasFormEntity paasFormEntity = getPaasFormExt(formId, businessType, corpid);
        return paasFormEntity;
    }

    /**
     * 获取表单主体，包括工单的
     * @param corpid 公司id
     * @param formId 表单id
     * @param businessType 业务类型
     * @return
     * @throws XbbException
     */
    public PaasFormEntityExt getPaasFormExt(Long formId, Integer businessType, String corpid) throws XbbException {
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKey(formId, corpid);
            if (Objects.isNull(workOrderFormEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            BeanUtil.copyProperties(workOrderFormEntity, paasFormEntityExt);
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            paasFormEntityExt.setBusinessType(businessType);
        } else {
            paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        }
        if (Objects.isNull(paasFormEntityExt)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        return paasFormEntityExt;
    }

    /**
     * 获取表单主体，包括工单的
     * @param corpid 公司id
     * @param formId 表单id
     * @param businessType 业务类型
     * @return
     * @throws XbbException
     */
    public PaasFormEntity getPaasFormIncludeDel(Long formId, Integer businessType, String corpid) throws XbbException {
        PaasFormEntity paasFormEntity = new PaasFormEntity();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            WorkOrderFormEntity workOrderFormEntity = workOrderFormModel.getByKeyIncludeDel(formId, corpid);
            if (Objects.isNull(workOrderFormEntity)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            BeanUtil.copyProperties(workOrderFormEntity, paasFormEntity);
        } else {
            paasFormEntity = paasFormModel.getByKeyIncludeDel(formId, corpid);
        }
        if (Objects.isNull(paasFormEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        return paasFormEntity;
    }

    /**
     * 获取表单列表，包括工单的
     * @param corpid 公司id
     * @param businessType 业务类型
     * @param formIds 表单id集合
     * @return
     * @throws XbbException exception
     */
    public List<PaasFormEntity> getPaasFormList(String corpid, Integer businessType, Collection<Long> formIds) throws XbbException {
        List<PaasFormEntity> paasFormEntityList = new ArrayList<>();
        if (StringUtil.isEmpty(corpid) || CollectionsUtil.isEmpty(formIds)) {
            return paasFormEntityList;
        }
        Map<String, Object> param = new HashMap<>(2 << 1);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(ParameterConstant.ID_IN, formIds);
        param.put(ParameterConstant.ORDER_BY_STR, "update_time desc");

        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            List<WorkOrderFormEntity> workOrderFormEntityList = workOrderFormModel.findEntitys(param);
            if (CollectionsUtil.isEmpty(workOrderFormEntityList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            try {
                BeanUtil.copyPropertiesList(workOrderFormEntityList, paasFormEntityList, PaasFormEntity.class);
            } catch (Exception e) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
        } else {
            paasFormEntityList = paasFormModel.findEntity(param);
        }
        if (CollectionsUtil.isEmpty(paasFormEntityList)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        return paasFormEntityList;
    }


    /**
     * 成本、单价、库存的精度、可见性、高级权限同步于产品
     * @param fieldAttrEntity 字段解释
     * @param corpid 公司id
     * @param userId 当前用户id
     */
    public void setProductAccuracy(FieldAttrEntity fieldAttrEntity, String corpid, String userId) throws XbbException {
        String costValue = paasRedisHelper.getValue(RedisPrefixConstant.PRODUCT_COST, corpid);
        String stockValue = paasRedisHelper.getValue(RedisPrefixConstant.PRODUCT_STOCK, corpid);
        String priceValue = paasRedisHelper.getValue(RedisPrefixConstant.PRODUCT_PRICE, corpid);
        ProductFieldPojo costField = new ProductFieldPojo();
        ProductFieldPojo stockField = new ProductFieldPojo();
        ProductFieldPojo priceField = new ProductFieldPojo();
        if (Objects.isNull(costValue) || Objects.isNull(stockValue) || Objects.isNull(priceValue)){
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessTypeNoEnable(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity entity : fieldAttrEntityList){
                if (Objects.equals(entity.getAttr(), ProductEnum.COST.getAttr())) {
                    BeanUtil.copyProperties(entity,costField);
                }
                if (Objects.equals(entity.getAttr(), ProductEnum.STOCK.getAttr())) {
                    BeanUtil.copyProperties(entity,stockField);
                }
                if (Objects.equals(entity.getAttr(), ProductEnum.PRICE.getAttr())) {
                    BeanUtil.copyProperties(entity,priceField);
                }
            }
            paasRedisHelper.setValue(RedisPrefixConstant.PRODUCT_COST,corpid,costField,RedisTimeConstant.LONG_DURATION);
            paasRedisHelper.setValue(RedisPrefixConstant.PRODUCT_STOCK,corpid,stockField,RedisTimeConstant.LONG_DURATION);
            paasRedisHelper.setValue(RedisPrefixConstant.PRODUCT_PRICE,corpid,priceField,RedisTimeConstant.LONG_DURATION);
        }else {
            costField = JSONObject.parseObject(costValue, ProductFieldPojo.class);
            stockField = JSONObject.parseObject(stockValue, ProductFieldPojo.class);
            priceField = JSONObject.parseObject(priceValue, ProductFieldPojo.class);
        }
        if (fieldAttrEntity == null || fieldAttrEntity.getSubForm() == null || fieldAttrEntity.getSubForm().getItems() == null) {
            return;
        }
        Iterator<? extends FieldAttrEntity> iterator = fieldAttrEntity.getSubForm().getItems().iterator();
        while (iterator.hasNext()) {
            FieldAttrEntity subFieldAttrEntity = iterator.next();
            if (Objects.equals(subFieldAttrEntity.getIsRedundant(), 0)) {
                if (Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.STOCK.getAttr())
                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.NUM.getAttr())
                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.OUTSTOCK_NUM.getAttr())
                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())
                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.INSTOCK_NUM.getAttr())

                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.WAIT_INSTOCK_NUM.getAttr())
                        || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.RETURN_NUM.getAttr())){
                    subFieldAttrEntity.setIntegerOnly(stockField.getIntegerOnly());
                    subFieldAttrEntity.setAccuracy(stockField.getAccuracy());
                    subFieldAttrEntity.setNumericalLimitsFlag(stockField.getNumericalLimitsFlag());
                    subFieldAttrEntity.setNumericalLimits(stockField.getNumericalLimits());
                    subFieldAttrEntity.setAmountFlag(stockField.getAmountFlag());
                }else if (Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRICE.getAttr()) || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SELLING_PRICE.getAttr())
                    || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SUBTOTAL.getAttr())){
                    // 采购合同 成本不可见采购单价默认塞个0
                    if(Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRICE.getAttr()) || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SELLING_PRICE.getAttr())){
                        if(Objects.equals(fieldAttrEntity.getAttrName(), PurchaseEnum.PRODUCT.getAttrName()) && Objects.equals(costField.getVisible(),0)){
                            DefaultAttrPoJo defaultAttrPoJo = new DefaultAttrPoJo();
                            defaultAttrPoJo.setDefaultValue(0D);
                            defaultAttrPoJo.setDefaultType(StringConstant.CUSTOM);
                            subFieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                        }
                        // 设置了高级可见规则
                        if (Objects.equals(fieldAttrEntity.getAttrName(), PurchaseEnum.PRODUCT.getAttrName()) && Objects.equals(costField.getVisible(),1) && Objects.equals(costField.getVisibleScopeEnable(),1)){
                            if(CollectionsUtil.isNotEmpty(costField.getVisibleScopeRule().getUser()) && Objects.equals(costField.getVisibleScopeRule().getType(),1) && costField.getVisibleScopeRule().getUser().contains(userId)){
                                DefaultAttrPoJo defaultAttrPoJo = new DefaultAttrPoJo();
                                defaultAttrPoJo.setDefaultValue(0D);
                                defaultAttrPoJo.setDefaultType(StringConstant.CUSTOM);
                                subFieldAttrEntity.setDefaultAttr(defaultAttrPoJo);
                            }
                        }
                    }
                    subFieldAttrEntity.setIntegerOnly(priceField.getIntegerOnly());
                    subFieldAttrEntity.setAccuracy(priceField.getAccuracy());
                    subFieldAttrEntity.setNumericalLimitsFlag(priceField.getNumericalLimitsFlag());
                    subFieldAttrEntity.setNumericalLimits(priceField.getNumericalLimits());
                    subFieldAttrEntity.setAmountFlag(priceField.getAmountFlag());
                }else if ((Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.COST.getAttr()) || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.TOTAL_COST.getAttr())) ||
                        (Objects.equals(fieldAttrEntity.getAttrName(), PurchaseEnum.PRODUCT.getAttrName()) && Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.PRICE.getAttr()) || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SELLING_PRICE.getAttr()) || Objects.equals(subFieldAttrEntity.getAttr(), SelectProductEnum.SUBTOTAL.getAttr()))) {
                    subFieldAttrEntity.setIntegerOnly(costField.getIntegerOnly());
                    subFieldAttrEntity.setAccuracy(costField.getAccuracy());
                    subFieldAttrEntity.setNumericalLimitsFlag(costField.getNumericalLimitsFlag());
                    subFieldAttrEntity.setNumericalLimits(costField.getNumericalLimits());
                    subFieldAttrEntity.setAmountFlag(costField.getAmountFlag());
                    //仅库存，同步可见，高级可见
                    subFieldAttrEntity.setVisible(costField.getVisible());
                    if (Objects.equals(costField.getIsOpen(),0)){
                        subFieldAttrEntity.setVisible(0);
                    }
                    subFieldAttrEntity.setVisibleScopeEnable(costField.getVisibleScopeEnable());
                    if (Objects.equals(costField.getVisibleScopeEnable(), 1)) {
                        if (!costField.getVisibleScopeRule().getRelative().isEmpty()) {
                            //高级可见负责人、协同人、创建人存在
                            if (costField.getVisibleScopeRule().getDep().isEmpty() && costField.getVisibleScopeRule().getRole().isEmpty() && costField.getVisibleScopeRule().getUser().isEmpty()) {
                                //高级可见部门、角色、人员全为空，字段不可见
                                //取巧做法，不对当前人可见
                                VisibleRulePoJo visibleScopeRule = new VisibleRulePoJo();
                                visibleScopeRule.setType(1);
                                visibleScopeRule.setUser(Collections.singletonList(userId));
                                subFieldAttrEntity.setVisibleScopeRule(visibleScopeRule);
                            } else {
                                //高级可见部门、角色、人员存在任何一个，移除负责人、协同人、创建人
                                costField.getVisibleScopeRule().setRelative(new ArrayList<>());
                                subFieldAttrEntity.setVisibleScopeRule(costField.getVisibleScopeRule());
                            }
                        }
                    }
                    subFieldAttrEntity.setVisibleScopeRule(costField.getVisibleScopeRule());
                }
            }
        }
    }



    /**
     * 选择产品字段
     * @param subFieldAttrEntity
     * @param corpid
     * @throws XbbException
     */
    public void setSelectProductItem(FieldAttrEntity subFieldAttrEntity,String corpid) throws XbbException {
        String attr = subFieldAttrEntity.getAttr();
        SelectProductEnum selectProductEnum = SelectProductEnum.getAttrByAttr(attr);
        Long formId = paasFormModel.getFormIdByBusinessType(corpid,XbbRefTypeEnum.PRODUCT.getCode());
        switch (selectProductEnum){
            case UNIT:
                List<ItemPoJo> itemPoJoList = dataDictionaryModel.getDictionaryList4Saas(DictionaryEnum.PRODUCT_UNIT,corpid,formId);
                subFieldAttrEntity.setItems(itemPoJoList);
                break;
            default:
                break;
        }
    }
    /**
     * 获取默认资金账户，如果没有设置则默认读取第一个
     * @param corpid
     * @param xbbRefTypeEnum
     * @return com.xbongbong.saas.domain.entity.FundAccountEntity
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public FundAccountEntity getDefaultFundAccount(String corpid, XbbRefTypeEnum xbbRefTypeEnum) {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        params.put("enable", EnableEnum.OPEN.getCode());
        List<FundAccountEntity> fundAccounts = fundAccountModel.findEntitys(params);
        if (CollectionsUtil.isEmpty(fundAccounts)) {
            return null;
        }
        //收入相关业务：回款单，其他收入单
        boolean in = Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET) || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_INCOME);
        //支出相关业务：付款单，其他支出单
        boolean out = Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET) || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_EXPENSE);
        for (FundAccountEntity e : fundAccounts) {
            if (in) {
                //收入相关使用收入的默认资金账户
                if (Objects.equals(BasicConstant.ONE, e.getIsPaymentDefault())) {
                    return e;
                }
            } else if (out) {
                //支出相关使用支出的默认资金账户
                if (Objects.equals(BasicConstant.ONE, e.getIsPayDefault())) {
                    return e;
                }
            }
        }
        //如果都没有默认值，则默认读取第一个
        return fundAccounts.get(0);
    }
    /**
     * 资金账户items处理
     * @param corpid 公司ID
     * @param businessType 业务类型，只有回款单、付款单、其他收入单、其他支出单需要用到该businessType，需要根据businessType判断是收入相关业务、还是支出相关业务，然后获取对应默认账户
     * @author zhouwq
     * @date 2020/3/5 15:49
     */
    public List<ItemPoJo> handleFundAccountItems(String corpid, Integer businessType) {
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(StringConstant.CORPID, corpid);
        params.put("del", DelEnum.NORMAL.getDel());
        List<FundAccountEntity> fundAccounts = fundAccountModel.findEntitys(params);
        List<ItemPoJo> itemPoJos = new ArrayList<>();
        //不同类型的回款单businessType，都统一汇总成XbbRefTypeEnum.PAYMENT_SHEET
        SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
        XbbRefTypeEnum xbbRefTypeEnum = sheetTypeEnum.getXbbRefTypeEnum();
        //收入相关业务：回款单，其他收入单
        boolean in = Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET) || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_INCOME);
        //支出相关业务：付款单，其他支出单
        boolean out = Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET) || Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_EXPENSE);
        for (FundAccountEntity e : fundAccounts) {
            ItemPoJo itemPoJo = new ItemPoJo();
            if (Objects.equals(e.getEnable(), EnableEnum.OPEN.getCode())) {
                if (in) {
                    //收入相关使用收入的默认资金账户
                    if (Objects.equals(BasicConstant.ONE, e.getIsPaymentDefault())) {
                        itemPoJo.setChecked(true);
                    }
                } else if (out) {
                    //支出相关使用支出的默认资金账户
                    if (Objects.equals(BasicConstant.ONE, e.getIsPayDefault())) {
                        itemPoJo.setChecked(true);
                    }
                }
                itemPoJo.setShowType(ShowTypeEnum.ALL.getCode());
            } else {
                itemPoJo.setShowType(ShowTypeEnum.EXCLUDE_NEW.getCode());
            }
            itemPoJo.setText(e.getName());
            itemPoJo.setValue(e.getId().toString());
            itemPoJos.add(itemPoJo);
        }
        return itemPoJos;
    }

    /**
     * @description 因为下拉框支字段增加了颜色属性，所以资金账户这边需要重新把颜色属性赋值一下
     *              原方法调用地方过多，所以将原方法重载
     * @author yanglei
     * @date 2023/2/2 16:29
     * @param corpid        公司id
     * @param businessType  业务类型
     * @param originItems   原始下拉框数据
     * @return List<ItemPoJo>
     */
    public List<ItemPoJo> handleFundAccountItems(String corpid, Integer businessType,List<ItemPoJo> originItems) {
        List<ItemPoJo> itemPoJos = handleFundAccountItems(corpid, businessType);
        if (CollectionsUtil.isNotEmpty(originItems)){
            Map<Object, String> colorMap = new HashMap<>();
            Map<Object, Map<String, List<ItemPoJo>>> subAttrMap = new HashMap<>();
            for (ItemPoJo originItem : originItems) {
                if (Objects.isNull(originItem.getValue())){
                    continue;
                }
                if (Objects.nonNull(originItem.getColor())){
                    colorMap.put(originItem.getValue(),originItem.getColor());
                }
                if (Objects.nonNull(originItem.getSubAttrList())){
                    subAttrMap.put(originItem.getValue(),originItem.getSubAttrList());
                }
            }
            for (ItemPoJo itemPoJo : itemPoJos) {
                itemPoJo.setColor(colorMap.get(itemPoJo.getValue()));
                itemPoJo.setSubAttrList(subAttrMap.getOrDefault(itemPoJo.getValue(),new HashMap<>()));
            }
        }
        return itemPoJos;
    }

    /**
     * 设置逻辑下拉字段的选项
     * @param selectExplainList
     * @param businessType
     */
    public void setComboItems(List<FieldAttrEntity> selectExplainList, Integer businessType) {
        selectExplainList.forEach(item->{
            if (Objects.equals(FieldTypeEnum.COMBO_NUM.getType(), item.getFieldType()) && Objects.isNull(item.getItems())) {
                List<ItemPoJo> itemList = getComboItems(item, businessType);
                item.setItems(itemList);
            }
        });
    }

    /**
     * 获取逻辑下拉字段的选项
     * @param item
     * @param businessType
     * @return 返回选项
     */
    public List<ItemPoJo> getComboItems(FieldAttrEntity item, Integer businessType) {
        if (Objects.equals(FieldTypeEnum.COMBO_NUM.getType(), item.getFieldType()) && CollectionsUtil.isEmpty(item.getItems())) {
            List<ItemPoJo> itemList = new ArrayList<>();
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                if (Objects.equals(CustomerManagementEnum.IS_PUBLIC.getAttr(), item.getAttr())) {

                    for (PublicEnum publicEnum: PublicEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                } else if (Objects.equals(CustomerManagementEnum.IS_ARCHIVED.getAttr(), item.getAttr())) {
                    for (ArchivedEnum publicEnum: ArchivedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }
            } else if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), businessType)) {
                if (Objects.equals(SalesOpportunityEnum.IS_ARCHIVED.getAttr(), item.getAttr())) {
                    for (ArchivedEnum publicEnum: ArchivedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }
            } else if (Objects.equals(XbbRefTypeEnum.INVOICE.getCode(), businessType)) {
                if (Objects.equals(InvoiceEnum.IS_RED.getAttr(), item.getAttr())) {
                    for (IsRedEnum publicEnum: IsRedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }
            }else if (Objects.equals(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), businessType)) {
                if (Objects.equals(PurchaseInvoiceEnum.IS_RED.getAttr(), item.getAttr())) {
                    for (IsRedEnum publicEnum: IsRedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }else if (Objects.equals(PurchaseInvoiceEnum.HAS_RED.getAttr(), item.getAttr())) {
                    for (HasRedEnum publicEnum: HasRedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }
            }else if (Objects.equals(XbbRefTypeEnum.QUOTATION.getCode(), businessType)) {
                if (Objects.equals(QuotationEnum.ARCHIVED.getAttr(), item.getAttr())) {
                    for (ArchivedEnum publicEnum: ArchivedEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }else if (Objects.equals(QuotationEnum.IS_NEW.getAttr(), item.getAttr())) {
                    for (NewEnum publicEnum: NewEnum.values()) {
                        ItemPoJo itemPoJo = new ItemPoJo(I18nMessageUtil.getMessage(publicEnum.getName()), publicEnum.getCode());
                        itemList.add(itemPoJo);
                    }
                }
            }
            return itemList;
        }
        return item.getItems();
    }

    /**
     * @Author sunshaoxiang
     * @Description 获取当前启用流程的阶段信息
     * @param saasMark
     * @param businessType
     * @param corpid
     * @param formId
     * @return List<ItemPoJo>
     **/
    public List<ItemPoJo> getEnableStageComboItems(Integer saasMark, Integer businessType, String corpid, Long formId) {
        FieldAttrEntity stageField = null;
        try {
            PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByFormId(formId, corpid);
            List<FieldAttrEntity> explainList = JSON.parseArray(paasFormExplain.getExplains(), FieldAttrEntity.class);
            stageField = explainList.stream().filter(field -> Objects.equals(field.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())).findFirst().orElse(null);
        } catch (XbbException e) {
            LOG.error("ProFormHelp.getEnableStageComboItems error", e);
        }
        StageProcessEntity stageProcessEntity;
        // 判断是否多版本启用，如果是多版本启用，那么获取默认的版本
        if (Objects.nonNull(stageField) && Objects.equals(stageField.getStageMultiVersion(), 1) && Objects.nonNull(stageField.getDefaultStageProcessId())) {
            stageProcessEntity = stageProcessModel.getByKey(stageField.getDefaultStageProcessId(), corpid);
        } else {
            stageProcessEntity = stageProcessModel.getEnableStageProcess(corpid, formId);
        }
        if (Objects.isNull(stageProcessEntity)) {
            return new ArrayList<>();
        }
        Long stageProcessId = stageProcessEntity.getId();
        return getItemPojoForStageEntity(corpid, formId, stageProcessId, businessType, saasMark, BasicConstant.ONE);
    }
    /**
     * 获取非工单的字段解释
     * @param formIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, PaasFormEntity> getFormMap(Collection formIdList, String corpid, Integer del) throws XbbException {
        Map<Long, PaasFormEntity> formExplainMap = new HashMap<>(formIdList.size());
        if (formIdList.isEmpty()) {
            return formExplainMap;
        }
        if (!formIdList.isEmpty()) {
            Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            explainParam.put(StringConstant.IDIN, formIdList);
            explainParam.put(StringConstant.CORPID, corpid);
            explainParam.put(StringConstant.DEL, del);
            List<PaasFormEntity> formExplainList = paasFormModel.findEntity(explainParam);
            if(formExplainList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            formExplainList.forEach((item)->{
                formExplainMap.put(item.getId(), item);
            });
        }
        return formExplainMap;
    }
    /**
     * 获取工单的字段解释
     * @param workOrderFormIdList
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long, WorkOrderFormEntity> getWorkOrderFormMap(Collection workOrderFormIdList, String corpid, Integer del) throws XbbException {
        Map<Long, WorkOrderFormEntity> workOrderFormMap = new HashMap<>(workOrderFormIdList.size());
        if (workOrderFormIdList.isEmpty()) {
            return workOrderFormMap;
        }
        if (!workOrderFormIdList.isEmpty()) {
            Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            explainParam.put(StringConstant.IDIN, workOrderFormIdList);
            explainParam.put(StringConstant.CORPID, corpid);
            explainParam.put(StringConstant.DEL, del);
            List<WorkOrderFormEntity> formExplainList = workOrderFormModel.findEntitys(explainParam);
            if(formExplainList == null){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            formExplainList.forEach((item)->{
                workOrderFormMap.put(item.getId(), item);
            });
        }
        return workOrderFormMap;
    }

    /**
     * 标签字段
     * @param fieldAttrEntity
     * @param corpid
     * @throws XbbException
     */
    public void setLabelDefaultValue(FieldAttrEntity fieldAttrEntity,String corpid) throws XbbException {
        DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
        if (Objects.nonNull(defaultAttr.getDefaultValue()) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())){
            Object defaultValue = defaultAttr.getDefaultValue();
            if (defaultValue instanceof  JSONArray){
                Boolean flag = false;
                JSONArray jsonArray1 = (JSONArray)defaultAttr.getDefaultValue();
                List<Long> labelIds = new ArrayList<>();
                for (Object item : jsonArray1) {
                    if (item instanceof JSONObject) {
                        // 兼容历史数据
                    } else  {
                        flag =true;
                        labelIds.add(Long.parseLong(item.toString()));
                    }
                }
                if (flag && labelIds.size()>0) {
                    List<LabelEntity> byLabelIds = labelModel.getByLabelIds(labelIds, corpid);
                    defaultAttr.setDefaultValue(byLabelIds);
                }
            }
        }
    }

    public void checkLabelExistis(List<Long> labelIds, String corpid, Integer num) throws XbbException {
        List<LabelEntity> labelEntities = labelModel.getByLabelIds(labelIds, corpid);
        Boolean flag = false;
        Boolean isRemove = false;
        StringBuilder stringBuilder = new StringBuilder();
        if (Objects.equals(num, BasicConstant.TWO) && labelIds.size() != labelEntities.size()){
            LOG.error("标签被彻底删除,不能设置为默认值");
            throw  new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120018, String.format(SystemLabelErrorCodeEnum.API_ERROR_1120018.getMsg(), stringBuilder.toString()));
        }
        for (LabelEntity item : labelEntities) {
            if (Objects.equals(num, BasicConstant.TWO)) {
                if (!labelIds.contains(item.getId())){
                    isRemove = true;
                    stringBuilder = new StringBuilder();
                    stringBuilder.append(item.getName());
                    break;
                }
            }
            if (Objects.equals(item.getEnable(), BasicConstant.ONE)) {
                flag = true;
                stringBuilder.append(item.getName()).append("  ");
            }
        }
        if (isRemove && Objects.equals(num, BasicConstant.TWO)){
            LOG.error("标签被彻底删除,不能设置为默认值");
            throw  new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120018, String.format(SystemLabelErrorCodeEnum.API_ERROR_1120018.getMsg(), stringBuilder.toString()));
        }
        if (flag && Objects.equals(num, BasicConstant.TWO)){
            LOG.error("标签被设置为默认值,不能删除");
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120017 ,String.format(SystemLabelErrorCodeEnum.API_ERROR_1120017.getMsg(), stringBuilder.toString()));
        }
        if (Objects.equals(num, BasicConstant.ONE)){
            LOG.error("标签已被移入回收站,不能保存");
            throw new XbbException(SystemLabelErrorCodeEnum.API_ERROR_1120016 ,String.format(SystemLabelErrorCodeEnum.API_ERROR_1120016.getMsg(), stringBuilder.toString()));
        }


    }
    /**
     * 预收/付款余额表单处理，formDataAddDTO中置为预收/付款属性
     *
     * @param formDataAddDTO 入参
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/11/21 13:31
     * @update 2021/1/9 by zcp 抽到help类内，方便经销商方法使用，且改为返回form实体，外部不用再次读取
     */
    public PaasFormEntityExt prePaymentHandle(FormDataAddDTO formDataAddDTO) throws XbbException {
        //预收/付款列表 businessType处理，把其余额处理成相应的预收/付款类型
        Integer businessType = formDataAddDTO.getBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum;
        if (Objects.equals(businessType, XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode())) {
            xbbRefTypeEnum = XbbRefTypeEnum.PAYMENT_SHEET;
            //预收款余额，置为预收款类型
            businessType = XbbRefTypeEnum.PREPAYMENT.getCode();
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PREPAY_BALANCE.getCode())) {
            xbbRefTypeEnum = XbbRefTypeEnum.PAY_SHEET;
            //预付款余额，置为预付款类型
            businessType = XbbRefTypeEnum.PREPAY.getCode();
        } else {
            //其他类型不处理，直接返回空
            return null;
        }
        formDataAddDTO.setBusinessType(businessType);
        formDataAddDTO.setSubBusinessType(businessType);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(xbbRefTypeEnum.getCode(), formDataAddDTO.getCorpid(), formDataAddDTO.getDistributorMark(), null);
        if ( paasFormEntityExt == null ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        formDataAddDTO.setFormId(paasFormEntityExt.getId());
        formDataAddDTO.setMenuId(paasFormEntityExt.getMenuId());
        formDataAddDTO.setAppId(paasFormEntityExt.getAppId());
        return paasFormEntityExt;
    }


    public FieldAndLogicPojo getOperatorObject(FieldAttrEntity fieldAttrEntity, Integer businessType, Class clazz) throws XbbException{
        // 开启、可见及业务规则可操作字段
        boolean flag = Objects.equals(1, fieldAttrEntity.getIsOpen()) && Objects.equals(1, fieldAttrEntity.getVisible()) && Objects.nonNull(RuleOperatorFieldEnum.getByCode(fieldAttrEntity.getFieldType()));
        // 系统字段
        JSONArray attrArray = RuleOperatorBusinessFieldEnum.getAttrsByCode(businessType);
        boolean sysFlag = Objects.equals(fieldAttrEntity.getIsRedundant(), BasicConstant.ZERO) && attrArray.contains(fieldAttrEntity.getAttr());
        // 自定义字段
        boolean cusFlag = Objects.equals(fieldAttrEntity.getIsRedundant(), BasicConstant.ONE);

        if (flag && (sysFlag || cusFlag)) {
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldAttrEntity.getFieldType());
            if (fieldTypeEnum != null) {
                Integer fieldType = fieldAttrEntity.getFieldType();

                FieldAndLogicPojo fieldAndLogicPojo = new FieldAndLogicPojo(fieldAttrEntity.getAttr(), fieldType, fieldAttrEntity.getAttrName(), fieldAttrEntity.getVisible(), fieldAttrEntity.getEditable());
                Object object = getPrivateConst(fieldTypeEnum.getAlias(), clazz);
                List<LogicPojo> logicList = getLogicList(object, 1);
                // 设置值类型
                fieldAndLogicPojo.setValueTypeList(getValueTypeList(fieldType));
                // 按照字段类型设置属性
                setFieldAttr(fieldAttrEntity, fieldAndLogicPojo);
                fieldAndLogicPojo.setLogicList(logicList);
                return fieldAndLogicPojo;
            }
        }
        return null;
    }

    /**
     * 获取逻辑运算符号
     * @param object
     * @param type
     * @return java.util.List<com.xbongbong.pro.formexplain.pojo.LogicPojo>
     * @author 吴峰
     * @date 2021/1/6 16:33
     * @throws XbbException
     */
    public List<LogicPojo> getLogicList(Object object, Integer type) {
        List<LogicPojo> logicList = new ArrayList<>();
        if (Objects.nonNull(object)) {
            String str = JSON.toJSONString(object);
            List<String> list = JSON.parseArray(str, String.class);
            list.forEach(item->{
                if (Objects.equals(0, type)) {
                    // 条件
                    ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(item);
                    if (Objects.nonNull(conditionEnum)) {
                        LogicPojo logicPojo = new LogicPojo(conditionEnum.getMemo(), conditionEnum.getSymbol());
                        logicList.add(logicPojo);
                    }
                } else {
                    // 操作
                    LogicalSymbolEnum conditionEnum = LogicalSymbolEnum.getBySymbol(item);
                    if (Objects.nonNull(conditionEnum)) {
                        LogicPojo logicPojo = new LogicPojo(conditionEnum.getMemo(), conditionEnum.getSymbol());
                        logicList.add(logicPojo);
                    }
                }

            });
        }
        return logicList;
    }

    public void setFieldAttr(FieldAttrEntity fieldAttrEntity, FieldAndLogicPojo fieldAndLogicPojo) {
        Integer fieldType = fieldAttrEntity.getFieldType();
        if (Objects.equals(FieldTypeEnum.DATETIME.getType(), fieldType)) {
            fieldAndLogicPojo.setDateType(fieldAttrEntity.getDateType());
        } else if (Objects.equals(FieldTypeEnum.NUM.getType(), fieldType)) {
            fieldAndLogicPojo.setAccuracy(fieldAttrEntity.getAccuracy());
            fieldAndLogicPojo.setIntegerOnly(fieldAttrEntity.getIntegerOnly());
            fieldAndLogicPojo.setNumericalLimitsFlag(fieldAttrEntity.getNumericalLimitsFlag());
            fieldAndLogicPojo.setNumericalLimits(fieldAttrEntity.getNumericalLimits());
        } else if (Objects.equals(FieldTypeEnum.ADDRESS.getType(), fieldType)) {
            fieldAndLogicPojo.setShowDetailAddress(fieldAttrEntity.getShowDetailAddress());
        } else if (Objects.equals(FieldTypeEnum.RADIO_GROUP.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.COMBO_CHECK.getType(), fieldType)
                || Objects.equals(FieldTypeEnum.CHECKBOX_GROUP.getType(), fieldType)) {
            fieldAndLogicPojo.setComboType(fieldAttrEntity.getComboType());
            fieldAndLogicPojo.setItems(fieldAttrEntity.getItems());
            fieldAndLogicPojo.setDefaultAttr(fieldAttrEntity.getDefaultAttr());
        } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldType)) {
            fieldAndLogicPojo.setLinkInfo(fieldAttrEntity.getLinkInfo());
        } else if (Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), fieldType)) {
            fieldAndLogicPojo.setLinkedType(fieldAttrEntity.getLinkedType());
        }
    }
    /**
     * 获取值类型
     */
    public List<ValueTypePojo> getValueTypeList(Integer fieldType) {
        List<ValueTypePojo> valueTypeList = new ArrayList<>();
        ValueTypePojo valueTypePojo = new ValueTypePojo(RuleValueTypeEnum.DYNAMIC_VALUE.getType(), RuleValueTypeEnum.DYNAMIC_VALUE.getName());
        valueTypeList.add(valueTypePojo);
        if (!Objects.equals(FieldTypeEnum.DATAID.getType(), fieldType)
                && !Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldType)
                && !Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldType)
                && !Objects.equals(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType(), fieldType)) {
            ValueTypePojo valueTypePojo1 = new ValueTypePojo(RuleValueTypeEnum.FIXED_VALUE.getType(), RuleValueTypeEnum.FIXED_VALUE.getName());
            valueTypeList.add(valueTypePojo1);
        }
        return valueTypeList;
    }
    /**
     * 反射获取私有变量的值
     * @param field
     * @param clazz
     * @return
     */
    public  Object getPrivateConst(String field, Class clazz){
        try {
            field = field.toUpperCase();
            Field f = clazz.getDeclaredField(field);
            f.setAccessible(true);
            return f.get(null);
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 获取关联数据和关联查询的关联表单
     * @author 吴峰
     * @date 2019/7/4 9:52
     * @param explainList
     * @param corpid
     * @return java.util.Map<java.lang.Long,com.xbongbong.paas.domain.entity.PaasFormExplainEntity>
     * @throws XbbException 业务异常
     */
    public Map<Long, PaasFormExplainEntity> getLinkFormExplain(List<FieldAttrEntity> explainList, String corpid) throws XbbException {
        Map<Long, PaasFormExplainEntity> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<LinkInfoPojo> linkInfoList = getLinkInfo(explainList);
        if (!linkInfoList.isEmpty()) {
            List<Long> formIdList = new ArrayList<>();
            for (LinkInfoPojo linkInfoPojo : linkInfoList) {
                if (Objects.isNull(linkInfoPojo)) {
                    continue;
                }
                if (!Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    formIdList.add(linkInfoPojo.getLinkFormId());
                }
            }
            if (formIdList.isEmpty()) {
                return formExplainMap;
            }
            if (!formIdList.isEmpty()) {
                Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                explainParam.put("formIdIn", formIdList);
                explainParam.put(StringConstant.CORPID, corpid);
                explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                List<PaasFormExplainEntity> formExplainList = paasFormExplainModel.list(explainParam);
                if(formExplainList == null){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                formExplainList.forEach((item)->{
                    formExplainMap.put(item.getFormId(), item);
                });
            }


        }
        return formExplainMap;
    }

    /**
     * 获取关联数据和关联查询的关联表单
     * @author 吴峰
     * @date 2019/7/4 9:52
     * @param explainList
     * @param corpid
     * @return java.util.Map<java.lang.Long,com.xbongbong.paas.domain.entity.PaasFormExplainEntity>
     * @throws XbbException 业务异常
     */
    public Map<Long, WorkOrderExplainEntity> getWorkOrderLinkFormExplain(List<FieldAttrEntity> explainList, String corpid) throws XbbException {
        Map<Long, WorkOrderExplainEntity> workOrderExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<LinkInfoPojo> linkInfoList = getLinkInfo(explainList);
        if (!linkInfoList.isEmpty()) {
            List<Long> workFormIdList = new ArrayList<>();
            for (LinkInfoPojo linkInfoPojo : linkInfoList) {
                if (Objects.isNull(linkInfoPojo)) {
                    continue;
                }
                if (Objects.equals(linkInfoPojo.getLinkSaasMark(), SaasMarkEnum.SAAS.getCode())
                        && Objects.equals(linkInfoPojo.getLinkBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    workFormIdList.add(linkInfoPojo.getLinkFormId());
                }
            }
            if (workFormIdList.isEmpty()) {
                return workOrderExplainMap;
            }
            if (!workFormIdList.isEmpty()) {
                Map<String, Object> explainParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                explainParam.put("formIdIn", workFormIdList);
                explainParam.put(StringConstant.CORPID, corpid);
                explainParam.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
                List<WorkOrderExplainEntity> formExplainList = workOrderExplainModel.list(explainParam);
                if(formExplainList == null){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                formExplainList.forEach((item)->{
                    workOrderExplainMap.put(item.getFormId(), item);
                });
            }

        }
        return workOrderExplainMap;
    }

    /**
     * 获取所有关联数据的字段，准备搜索各个业务的数据
     * @param explainList
     * @return
     */
    public static List<LinkInfoPojo> getLinkInfo(List<? extends FieldAttrEntity> explainList) {
        List<LinkInfoPojo> linkInfoList = new ArrayList<>();
        explainList.forEach(item->{
            if (ExplainUtil.isSubForm(item.getFieldType()) && Objects.nonNull(item.getSubForm()) && Objects.nonNull(item.getSubForm().getItems())) {
                List<? extends FieldAttrEntity> subExplainList = item.getSubForm().getItems();
                linkInfoList.addAll(getLinkInfo(subExplainList));
            } else if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), item.getFieldType())) {
                linkInfoList.add(item.getLinkInfo());
            }
        });
        return linkInfoList;
    }

    /**
     * 获取所有关联数据的字段，准备搜索各个业务的数据
     * @param explainList
     * @return
     */
    public static List<LinkInfoPojo> getLinkInfoNoSubForm(List<? extends FieldAttrEntity> explainList) {
        List<LinkInfoPojo> linkInfoList = new ArrayList<>();
        explainList.forEach(item->{
            if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), item.getFieldType()) || Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), item.getFieldType())) {
                linkInfoList.add(item.getLinkInfo());
            }
        });
        return linkInfoList;
    }

    /**
     * 列表新建编辑保存详情，部分字段处理
     * 例如客户合同状态
     * @param explainList
     * @param businessType
     * @param corpid
     * @param formId
     * @return List<FieldAttrEntity>
     */
    public List<FieldAttrEntity> handleExplainList(List<FieldAttrEntity> explainList, Integer businessType, String corpid, Long formId) throws XbbException {
        int i = 0;
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            List<ItemPoJo> itemList = getItem(fieldAttrEntity, businessType, corpid, formId);
            fieldAttrEntity.setItems(itemList);
            explainList.set(i, fieldAttrEntity);
            i++;
        }
        return explainList;
    }

    /**
     * 获取自定义子表单检索字段
     * @param linkInfoPojo
     */
    public static Set<String>  getFieldList(LinkInfoPojo linkInfoPojo) {
        Set<String> fieldList = new HashSet<>();
        if (Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), linkInfoPojo.getLinkBusinessType())) {
            // 关联表单是产品时，则检索所有字段，因为后续解析需要用到其他字段，所以需要都检索
            return fieldList;
        }
        List<LinkedAttrPoJo> linkedAttr = linkInfoPojo.getLinkedAttr();
        fieldList.add(linkInfoPojo.getLinkKey());
        if (CollectionsUtil.isEmpty(linkedAttr)) {
            // 显示字段为空，则返回主键字段
            return fieldList;
        }

        linkedAttr.forEach(item->{
            if (!Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                if (ExplainUtil.isSubForm(item.getFieldType()) && CollectionUtils.isNotEmpty(item.getSubForm().getItems())) {
                    // 客户电话等存在data中的字段
                    List<? extends FieldAttrEntity> subList = item.getSubForm().getItems();
                    subList.forEach(subItem->{
                        fieldList.add(subItem.getParentAttr() + StringConstant.POINT + subItem.getAttr());
                    });
                } else {
                    fieldList.add(item.getAttr());
                }
            }
        });
        return fieldList;
    }

    /**
     * 获取自定义子表单检索字段
     * @param linkedAttr
     */
    public static Set<String>  getSubFieldList(List<LinkedAttrPoJo> linkedAttr) {
        Set<String> fieldList = new HashSet<>();
        if (CollectionsUtil.isEmpty(linkedAttr)) {
            return fieldList;
        }
        linkedAttr.forEach(item->{
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                List<? extends FieldAttrEntity> subList = item.getSubForm().getItems();
                subList.forEach(subItem->{
                    fieldList.add(subItem.getAttr());
                });
            }
        });
        return fieldList;
    }

    /**
     * 获取自定义子表单检索字段
     * @param linkedAttr
     */
    public static Set<String>  getParentFieldList(List<LinkedAttrPoJo> linkedAttr) {
        Set<String> fieldList = new HashSet<>();
        if (CollectionsUtil.isEmpty(linkedAttr)) {
            return fieldList;
        }
        linkedAttr.forEach(item->{
            if (Objects.equals(FieldTypeEnum.SUB_FORM.getType(), item.getFieldType())) {
                fieldList.add(item.getAttr());
            }
        });
        return fieldList;
    }

    public List<PaasFormDataEntityExt> getFormDataList(List<Object> ids, String corpid, IndexTypeEnum indexTypeEnum, Set<String> fieldList, Integer saasMark, Integer businessType) throws XbbException {
        if (ids.isEmpty()) {
            return new ArrayList<>();
        }
        if(ids.size() > EsNormalConstant.FIND_NUM){
            throw  new XbbException(SystemErrorCodeEnum.API_ERROR_100072);
        }
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery("dataId", ids));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType()));
        //分页
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, ids.size());
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        searchRequest.source(sourceBuilder);
        List<PaasFormDataEntityExt> formDataList = xbbElasticsearchRestTemplate.queryForList(pageRequest,searchRequest, PaasFormDataEntityExt.class);
        if (CollectionsUtil.isNotEmpty(fieldList) && CollectionsUtil.isNotEmpty(formDataList)) {
            Set<Long> parentIdList = new HashSet<>();
            formDataList.forEach(item->{
                parentIdList.add(item.getDataId());
            });
            Integer subPageSize = parentIdList.size() * PaasConstant.SUB_FORM_MAX_LARGE;

            List<PaasFormSubDataEntity> paasFormSubDataList = paasFormSubDataEsModel.getSubDataByParentId(corpid, saasMark, businessType,
                    new ArrayList<>(fieldList), null, parentIdList, 1, subPageSize, IndexTypeEnum.getSubEnum(indexTypeEnum));
            // 封装子表单数据进主表数据
            FormSubDataUtil.setSubData(formDataList, paasFormSubDataList);
        }
        return formDataList;
    }

    /**
     * 获取对应业务的数据
     */
    public Map<String, PaasFormDataEntityExt> ruleGetLinkDataOfBusinessType(LinkResultDataDTO linkResultDataDTO, LinkResultDataVO linkResultDataVO) throws XbbException {
        // key为：saas是“业务类型_表单数据id” paas是“表单数据id”
        Map<String, PaasFormDataEntityExt> formDataMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Object> linkDataSet = linkResultDataVO.getLinkDataSet();
        if (linkDataSet.isEmpty()) {
            return formDataMap;
        }
        // 获取所有的关联数据的表单
        List<FieldAttrEntity> explainList = linkResultDataVO.getExplainList();
        List<LinkInfoPojo> linkInfoList = getLinkInfo(explainList);
        Map<Integer, LinkInfoPojo> saasLinkInfoMap = new HashMap<>(linkInfoList.size());
        List<LinkInfoPojo> paasLinkInfoList = new ArrayList<>();
        List<Long> formIdList = new ArrayList<>();
        for (LinkInfoPojo linkInfoPojo : linkInfoList) {
            formIdList.add(linkInfoPojo.getLinkFormId());
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), linkInfoPojo.getLinkSaasMark())) {
                saasLinkInfoMap.put(linkInfoPojo.getLinkBusinessType(), linkInfoPojo);
            } else {
                paasLinkInfoList.add(linkInfoPojo);
            }
        }
        List<Object> ids = new ArrayList<>();
        linkDataSet.forEach((item)->{
            ids.add(item);
        });
        String corpid = linkResultDataDTO.getCorpid();
        Iterator<Integer> saasIterator = saasLinkInfoMap.keySet().iterator();

        while (saasIterator.hasNext()) {
            LinkInfoPojo linkInfoPojo = saasLinkInfoMap.get(saasIterator.next());
            Set<String> fieldList = new HashSet<>();
            // 获取子表单检索字段
            fieldList.add("data");
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, linkInfoPojo.getLinkBusinessType(), linkInfoPojo.getLinkSaasMark());
            List<PaasFormDataEntityExt> dataList = getFormDataList(ids, corpid, indexTypeEnum, fieldList, linkInfoPojo.getLinkSaasMark(), linkInfoPojo.getLinkBusinessType());

            dataList.forEach(item->{
                String key = linkInfoPojo.getLinkBusinessType() + "_" + item.getDataId();
                formDataMap.put(key, item) ;
            });
        }
        if (CollectionsUtil.isNotEmpty(paasLinkInfoList)) {
            Set<String> fieldList = new HashSet<>();
            // 获取子表单检索字段
            fieldList.add("data");
            List<PaasFormDataEntityExt> dataList = getFormDataList(ids, corpid, IndexTypeEnum.IDX_FORM_DATA, fieldList, SaasMarkEnum.PAAS.getCode(), 0);
            dataList.forEach(item -> {
                String key = item.getDataId().toString();
                formDataMap.put(key, item);
            });
        }
        return formDataMap;
    }

    /**
     * 查询单条数据，判断查询出来的configValue的状态码是1还是0，1则返回true,0则返回false
     * @param corpid
     * @param config
     * @param formId
     * @return
     * @throws XbbException
     */
    public Boolean getClueSingleRuleList(String corpid, String config, Long formId) throws XbbException {
        Boolean flag = true;
        FormConfigEntity configEntity = formConfigModel.getEntityByFormId(corpid,formId,config);
        ClueRuleSettingEnum ruleSettingEnum = ClueRuleSettingEnum.getByConfig(config);
        if (Objects.isNull(configEntity)) {
            flag = Objects.equals(ruleSettingEnum.getConfigValue(), StringConstant.POSITIVE_NUMBER);
        }
        if (Objects.nonNull(configEntity) && !Objects.equals(configEntity.getConfigValue(), StringConstant.POSITIVE_NUMBER) ) {
            flag = false;
        }
        return flag;
    }


    /**
     * Description:
     * @param corpid
	 * @param config
	 * @param formId
     * @return java.lang.Boolean
     * @throws
     * @author 魏荣杰
     * @date 2021/7/20 19:36
     * @since
     */
    public Boolean getSingleRuleList(String corpid, String config, Long formId) throws XbbException {
        Boolean flag = true;
        FormConfigEntity configEntity = formConfigModel.getEntityByFormId(corpid,formId,config);
        RuleSettingEnum ruleSettingEnum = RuleSettingEnum.getByConfig(config);
        if (Objects.isNull(configEntity)) {
            flag = Objects.equals(ruleSettingEnum.getConfigValue(), StringConstant.POSITIVE_NUMBER);
        }
        if (Objects.nonNull(configEntity) && !Objects.equals(configEntity.getConfigValue(), StringConstant.POSITIVE_NUMBER) ) {
            flag = false;
        }
        return flag;
    }

    /**
     * @Author sunshaoxiang
     * @Description 从阶段entity解析得到itemPojo
     * @param corpid
     * @param formId
     * @param stageProcessId
     * @param businessType
     * @param saasMark
     * @param enable
     * @return List<ItemPojo>
     **/
    public List<ItemPoJo> getItemPojoForStageEntity(String corpid, Long formId, Long stageProcessId, Integer businessType, Integer saasMark, Integer enable){
        Map<String, Object> params = new HashMap<>();
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.FORMID, formId);
        params.put(ParameterConstant.STAGE_PROCESS_ID, stageProcessId);
        params.put(ParameterConstant.DEL, BasicConstant.ZERO);
        params.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT + " " + SortOrder.DESC);
        params.put(ParameterConstant.ENABLE, enable);
        StageHandle stageHandle = stageHandleFactory.getStageHandle(saasMark, businessType);
        List<? extends PaasStageEntity> paasStageEntities = stageHandle.findEntitys(params);

        List<ItemPoJo> itemList = new ArrayList<>();
        if (CollectionsUtil.isEmpty(paasStageEntities)) {
            return itemList;
        }
        for (PaasStageEntity paasStageEntity : paasStageEntities) {
            ItemPoJo itemPoJo = new ItemPoJo();
            itemPoJo.setText(paasStageEntity.getName());
            itemPoJo.setValue(paasStageEntity.getCode());
            itemPoJo.setStageId(paasStageEntity.getId());
            itemPoJo.setStageProcessId(paasStageEntity.getStageProcessId());
            itemPoJo.setAllowSkipStage(paasStageEntity.getAllowSkipStage());
            itemPoJo.setStageType(paasStageEntity.getType());
            itemPoJo.setEnable(paasStageEntity.getEnable());

            //阶段任务下如果没有没有任务，应该取跳出比例，这里原本会多一次任务表的查询。但是因为阶段跳转的时候会覆盖这里的阶段比例，所以这里干脆就不查了，以免影响数据库性能
            itemPoJo.setStageRatio(paasStageEntity.getIntoProportion());

            if (Objects.equals(paasStageEntity.getIsDefault(), BasicConstant.ONE)) {
                itemPoJo.setChecked(true);
            }
            if (CollectionsUtil.isNotEmpty(paasStageEntity.getLinkOption())) {
                itemPoJo.setFieldMap(JSON.parseArray(JSON.toJSONString(paasStageEntity.getLinkOption()), String.class));
            }
            itemList.add(itemPoJo);
        }
        return itemList;
    }

        /**
     * Description: 补充data中少了的attr key值的data数据，用于编辑数据新增字段数据后，被拒绝后数据还原使用，es的更新需要key值
     * @param sourceObject 来源data
	 * @param targetObject 目标data，需要填充attr的data
     * @return void
     * @throws
     * @author 魏荣杰
     * @date 2023/2/23 10:53
     * @since
     */
    public void replenishAttrForBackupData(JSONObject sourceObject, JSONObject targetObject) {
        sourceObject.forEach((v, k) -> {
            if (!targetObject.containsKey(v)) {
                targetObject.put(v, null);
            }
        });
    }
}
